"""
encoding:utf-8
time:2024/09/01
version:0.1
username: thunderstorm_chen
message: 本地日志工具库
"""
import os
import socket
import logging
from datetime import datetime


class FunctionNameFilter(logging.Filter):
    def filter(self, record):
        record.function_name = record.funcName
        return True


class CodePositionFilter(logging.Filter):
    def filter(self, record):
        record.code_position = f'{record.pathname}:{record.lineno}'
        return True


class Record(logging.Logger):
    @staticmethod
    def get_equipment_ip():
        """
        获取设备IP地址
        :return: 设备IP地址
        """
        try:
            ip = socket.gethostbyname(socket.gethostname())
            return ip
        except socket.gaierror as e:
            return f"ERROR: 获取设备IP地址时发生错误: {e}"

    def __init__(self, name, path_format=r"[script_name]\[datetime]\[ip].log",
                 level=logging.INFO, console=False):
        # 默认日志存放路径
        base_path = "../LogFile"
        # 格式化路径
        formatted_path = path_format.replace('[script_name]', name) \
            .replace('[datetime]', datetime.now().strftime('%Y-%m-%d')) \
            .replace('[ip]', self.get_equipment_ip())

        # 构建完整路径
        full_path = os.path.join(base_path, formatted_path)
        dir_path = os.path.dirname(full_path)

        # 创建目录
        os.makedirs(dir_path, exist_ok=True)

        # 调用父类构造函数
        super().__init__(name, level)

        # 创建文件处理器
        file_handler = logging.FileHandler(full_path)
        file_handler.setLevel(level)

        # 创建自定义过滤器
        function_name_filter = FunctionNameFilter()
        code_position_filter = CodePositionFilter()

        # 创建格式化器
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s '
            '[%(code_position)s] '
            '- %(message)s')

        # 添加过滤器和格式化器到处理器
        file_handler.addFilter(function_name_filter)
        file_handler.addFilter(code_position_filter)
        file_handler.setFormatter(formatter)

        # 添加处理器到日志记录器
        self.addHandler(file_handler)

        # 添加控制台输出
        if console:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(level)
            console_handler.addFilter(function_name_filter)
            console_handler.addFilter(code_position_filter)
            console_handler.setFormatter(formatter)
            self.addHandler(console_handler)

# 示例用法
# if __name__ == '__main__':
#     log = Record('example_script', base_path='E:\\海通证券\\所有日志',
#                      path_format=r"[script_name]\[datetime]\[ip].log",
#                      level=logging.DEBUG, console=True)
#
#     log.info('This is an info message.')
#     log.debug('This is a debug message.')
#     log.error('This is an error message.')
#     log.warning('This is a warning message.')
